import React, { useState, useEffect } from 'react'
import SelectSku from './components/SelectSku';
import Contain from './components/contain';
import { AtIcon } from 'taro-ui'
import { View, Swiper, SwiperItem, Text, RichText } from '@tarojs/components'
import { Space, Swiper as SwiperInfo } from '@/components/UiComponents';
import Tabs from '@/components/Tabs'
import DataTime from './components/DateTime'
import Router from '@/utils/router';
import Taro, { getCurrentInstance, useShareAppMessage, useShareTimeline } from '@tarojs/taro'
import { backgroundObj, toast } from '@/utils/utils'
import "taro-ui/dist/style/components/icon.scss";
import 'taro-ui/dist/style/components/accordion.scss'
import { AtAccordion, AtList, AtListItem } from 'taro-ui'
import { formatRichText } from '@/utils/utils';
import "taro-ui/dist/style/components/list.scss";
import { fakeUserReserve } from '@/server/shop'
import MaskCode from './components/MaskCode';
const offline = (props) => {
  const { params } = getCurrentInstance().router
  const { data = {}, reload } = props
  const { organizationId = '1', goodsId = '', fromGoodsId = '' } = params
  const { goodsSkuList = [], containPackageGoodsList
    = [], goodsBaseInfo = {}, offlineInfo = {}, goodsContentList = [], secKill = {}, goodsPackageList = [], userGoodsCommerce
    , materialInfoList = [], userGoodsOwnerInfo = [] } = data
  const { ownerFlag } = userGoodsOwnerInfo
  const { authCodeFlag, price, skuHighPrice, goodsName, goodsDesc, content, picture = '', goodsType = 'offline', priceType, oriPrice } = goodsBaseInfo
  const { stock } = offlineInfo
  const [materialInfoVisible, setMaterialInfoVisible] = useState(true)
  const [visible, setVisible] = useState(false)
  const [activeKey, setActiveKey] = useState('detail')
  const [tabList, setTabList] = useState([{ value: 'detail', label: '详情' }])
  const [containVisible, setContainVisible] = useState(false)
  const [maskCodeVisible, setMaskCodeVisible] = useState(false)
  const [skuData, setSkuData] = useState({ selectobj: {}, selectData: {} })
  const { selectobj, selectData, count = '1' } = skuData
  const { propertyDesc = '', id: skuId, price: skuPrice } = selectobj
  useShareAppMessage(() => {
    let organizationId = Taro.getStorageSync("organizationId")
    return {
      title: goodsName,
      path: `pages/index/redirect/index?organizationId=${organizationId}&openType=wechatShare&type=shopDetail&goodsId=${goodsId}`, // 分享的路径
    };
  })
  useShareTimeline(() => {
    let organizationId = Taro.getStorageSync("organizationId")
    return {
      title: goodsName,
      path: `pages/index/redirect/index?organizationId=${organizationId}&openType=wechatShare&type=shopDetail&goodsId=${goodsId}`, // 分享的路径
    };
  })

  useEffect(() => {
    setSkuData({
      ...skuData,
      selectData: goodsSkuList.reduce((item, val) => {
        const { propertyDesc } = val
        const newList = propertyDesc.split(',')
        newList.forEach(o => {
          const newData = o.split(':')
          if (!item[newData[0]]) {
            item[newData[0]] = []
            if (!item[newData[0]].includes(newData[1])) {
              item[newData[0]].push(newData[1])
            }

          }
          else {
            if (!item[newData[0]].includes(newData[1])) {
              item[newData[0]].push(newData[1])
            }
          }
        })
        return item
      }, {})
    })
  }, [goodsSkuList.length]);
  useEffect(() => {
    if (goodsContentList.length !== 0 && materialInfoList.length !== 0) {
      setTabList([{ value: 'detail', label: '详情' }, { label: '目录', value: 'goodsContent' }, { value: 'materialInfo', label: '资料' }])
    }
    else if (goodsContentList.length !== 0) {
      setTabList([{ value: 'detail', label: '详情' }, { label: '目录', value: 'goodsContent' }])
    }
    else if (materialInfoList.length !== 0) {
      setTabList([{ value: 'detail', label: '详情' }, { value: 'materialInfo', label: '资料' }])
    }
    else {
      setTabList([{ value: 'detail', label: '详情' }])
    }
  }, [data])
  const handleUserResave = (id) => {
    fakeUserReserve({
      secKillId: id
    }).then(val => {
      reload()
    })
  }
  const renderButton = () => {
    if (Object.keys(secKill).length > 0) {
      const { status, reserveFlag, userReserveFlag, id } = secKill
      if (status === '1' && reserveFlag === '1' && userReserveFlag !== '1') {
        return <View className='ShopDetail_btn'>
          <View className='ShopDetail_btn_box'>
            <View className={'ShopDetail_info_bigBtn'} onClick={() => handlePay()
            }>立即购买</View>
          </View>
        </View>
        //未预约并且不可再预约
      } else if (status !== '1' && reserveFlag === '1' && userReserveFlag === '1') {
        return <View style={{ opacity: 0.3 }} className='ShopDetail_btn'>
          <View className='ShopDetail_btn_box'>
            <View className={'ShopDetail_info_bigBtn'}>已预约</View>
          </View>
        </View>
      } else if (status !== '1' && reserveFlag === '1' && userReserveFlag !== '1') {
        return <View className='ShopDetail_btn'>
          <View className='ShopDetail_btn_box'>
            <View className={'ShopDetail_info_bigBtn'} onClick={() => handleUserResave(id)
            }>立即预约</View>
          </View>
        </View>
      } else {
        return <View className='ShopDetail_btn'>
          <View className='ShopDetail_btn_box'>
            <View className={authCodeFlag === '1' && ownerFlag === '0' ? 'ShopDetail_info_btn' : 'ShopDetail_info_bigBtn'} onClick={() => handlePay()
            }>立即购买</View>
            {authCodeFlag === '1' && ownerFlag === '0' && <View onClick={() => {
              setMaskCodeVisible({
                show: true,
                detail: goodsBaseInfo
              })
            }} className='playCode_btn'>口令兑换</View>}
          </View>

        </View>
      }
    }
    else {
      return <View className='ShopDetail_btn'>
        <View className='ShopDetail_btn_box'>
          <View className={authCodeFlag === '1' && ownerFlag === '0' ? 'ShopDetail_info_btn' : 'ShopDetail_info_bigBtn'} onClick={() => handlePay()
          }>立即购买</View>
          {authCodeFlag === '1' && ownerFlag === '0' && <View onClick={() => {
            setMaskCodeVisible({
              show: true,
              detail: goodsBaseInfo
            })
          }} className='playCode_btn'>口令兑换</View>}
        </View>

      </View>
    }
  }
  const Tag = () => {
    return <View className='shopDetail_tag'>服务类商品</View>
  }
  const renderIcon = (type, url) => {

    if (type === 'image') {
      return 'file-png'
    } else if (type === 'video') {
      return 'file-video'
    } else if (type === 'voice') {
      return 'file-audio'
    }
    else if (type === 'ebook') {
      return 'file-new'
    } else {
      function getFileExtension(fileName) {
        // 使用正则表达式匹配文件名中的后缀部分
        const regex = /(?:\.([^.]+))?$/;
        const result = regex.exec(fileName);

        // 提取匹配到的后缀，如果没有后缀则返回空字符串
        const extension = result ? result[1] : '';

        return extension;
      }
      return `file-${getFileExtension(url)}`
    }
  }
  const RenderShopCard = (props) => {
    const { data } = props
    const { goodsName, goodsCover } = data
    return <View className='renderShopCard_box'>
      <View className='renderShopCard_profile' style={backgroundObj(goodsCover)} ></View>
      <View className='renderShopCard_content'>
        {goodsName}
      </View>
    </View>
  }
  const RenderShopContainItems = containPackageGoodsList.map((item, index) => {
    const { cover, goodsName, goodsDesc, id } = item
    return <SwiperItem key={index}>
      <View className='Shopcontain_head'>包含该课程的还有</View>
      <View className='Shopcontain_content' onClick={(e) => {
        e.stopPropagation();
        Router('shopDetail', { args: { goodsId: id } })
      }}>
        <View style={backgroundObj(cover.split(',')[0])} className='Shopcontain_Profile'></View>
        <View className='Shopcontain_body font_hide'>
          <View className='Shopcontain_body_title font_hide'>{goodsName}</View>
          <View className='Shopcontain_body_desc'>{goodsDesc}</View>
        </View>
      </View>
    </SwiperItem>
  })
  const renderContent = {
    detail:
      <View>
        {containPackageGoodsList.length > 0 && <Swiper className='Shopcontain_goods_box' >
          {RenderShopContainItems}
        </Swiper>}

        <RichText style={{ marginTop: 12 }} nodes={formatRichText(content)}></RichText>
      </View>,
    goodsContent: <View> {goodsContentList.map((item, index) => {
      const { sectionId, sectionName, sectionGoodsList = [] } = item
      if (sectionName && sectionId) {
        return <AtAccordion
          open={true}
          key={sectionId} title={sectionName}
        >
          <AtList hasBorder={false}>
            {sectionGoodsList.map((val, o) => {
              return <RenderShopCard key={o} data={val}></RenderShopCard>
            })}
          </AtList>
        </AtAccordion>

      }
      else {
        return <RenderShopCard key={index} data={item}></RenderShopCard>
      }
    })}</View>,
    materialInfo: <AtAccordion
      open={materialInfoVisible}
      onClick={() => setMaterialInfoVisible(!materialInfoVisible)}
      title='资料列表'
    >
      <AtList hasBorder={false}>
        {materialInfoList.map((item, index) => {
          const { materialName, contentType, content } = item
          const { url } = JSON.parse(content);
          return <AtListItem
            onClick={() => toast('购买后可观看')}
            key={index}
            title={materialName}
            iconInfo={{ value: renderIcon(contentType, url) }}
          />
        })}
      </AtList>
    </AtAccordion>
  }[activeKey]
  console.log(skuData)
  const Seckill = () => {
    const { preheatFlag, secKillPrice, secKillTag, secKillStartTime, secKillEndTime, secKillStock, preheatHour, status } = secKill
    if (secKillStartTime && secKillEndTime) {
      let nowTime = parseInt(new Date().getTime() / 1000);
      let startTime = parseInt(new Date(secKillStartTime.replace(/-/g, '/')).getTime() / 1000)
      if (status === '1') {
        return <View className='Seckill_box'>
          <View className='Seckill_left_box'>
            <View className='Seckill_left_price'>
              <View className='Seckill_left_priceCount'>¥{secKillPrice}</View>
              <View className='Seckill_left_tag'>{secKillTag || '秒杀'}</View>
              <View className='Seckill_left_scort'>还剩{secKillStock}个</View>
            </View>
            <View className='Seckill_left_oldPrice'>{price}</View>
          </View>
          <View className='Seckill_right_box'>
            <DataTime type='start' preheatFlag={preheatFlag} startTime={secKillStartTime} endTime={secKillEndTime}></DataTime>
          </View>
        </View>
      } else if (status === '2') {
        return <View className='Seckill_box'>
          <View className='Seckill_left_box'>
            <View className='Seckill_left_price'>
              <View className='Seckill_left_priceCount'>¥{secKillPrice}</View>
              <View className='Seckill_left_tag'>{secKillTag || '秒杀'}</View>
              <View className='Seckill_left_scort'>还剩{secKillStock}个</View>
            </View>
            <View className='Seckill_left_oldPrice'>{'¥' + price}</View>
          </View>
          <View className='Seckill_right_box'>
            <DataTime type='before' startTime={secKillStartTime} endTime={secKillEndTime}></DataTime>
          </View>
        </View>

      } else {
        return <View className='ShopDetail_content_price'>{skuHighPrice ? `${price} - ${skuHighPrice}` : priceType === 'free' ? '免费' : price} <Text className='ShopDetail_oriPrice_box' style={{ color: '#999999', textDecoration: 'line-through' }}>原价：{oriPrice}</Text></View>
      }
    }
    else if (userGoodsCommerce) {
      const { livePrice, liveStock } = userGoodsCommerce
      return <View className='ShopDetail_content_price'>{livePrice}<Text className='ShopDetail_oriPrice_box' style={{ paddingLeft: 4, color: '#999999', textDecoration: 'line-through' }}>原价：{oriPrice}</Text></View>
    }
    else {
      return <View className='ShopDetail_content_price'>{skuHighPrice ? skuPrice ? skuPrice : `${price}起` : priceType === 'free' ? '免费' : price}
        <Text className='ShopDetail_oriPrice_box' style={{ color: '#999999', textDecoration: 'line-through' }}>原价：{oriPrice}</Text>
      </View>
    }

  }
  const handlePay = () => {
    if (goodsSkuList.length > 0 && !propertyDesc) {
      return toast('请选择商品规格后再支付')
    }
    else if (goodsSkuList.length > 0 && propertyDesc) {
      Router('payOrder', {
        args: {
          goodsId: goodsId,
          organizationId: organizationId,
          skuId: skuId,
          count: count,
          fromGoodsId
        }
      })
    }
    else {
      Router('payOrder', {
        args: {
          goodsId: goodsId,
          organizationId: organizationId,
          fromGoodsId
        }
      })
    }

  }
  return (
    <View className='ShopDetail_box'>
      <SwiperInfo className='ShopDetail_swiper_box' list={picture.split(',')}></SwiperInfo>
      <View className='ShopDetail_content_info'>
        <View className='ShopDetail_content'>
          {Seckill()}
          <View className='ShopDetail_content_title'>{goodsName} </View>
          <View className='ShopDetail_content_desc'>{goodsDesc}</View>
        </View>
        {/* {goodsType === 'offline' && <View className='ShopDetail_shop_count'>
          <View className='ShopDetail_count_right'>
            剩余 {stock}</View>
        </View>} */}
        {goodsSkuList.length > 0 && <View className='ShopDetail_sku' onClick={() => { setVisible(true) }}>
          <View className='ShopDetail_sku_left'>
            {propertyDesc ? '已选: ' : '选择:'}
            <Text className='ShopDetail_sku_leftSpan'>{propertyDesc ? propertyDesc : Object.keys(selectData).toString()}</Text>
          </View>
          <View className='ShopDetail_sku_right'>  {propertyDesc ? null : `共有${Object.values(selectData).length ? Object.values(selectData)[0].length : ''}种${Object.keys(selectData)[0]}可选`}</View>
        </View>}
        {goodsPackageList.length > 0 && <View className='ShopDetail_sku' onClick={() => { setContainVisible(true) }}>
          <View className='ShopDetail_sku_left'>
            套餐：内含{goodsPackageList.length}种商品
          </View>
          <View className='ShopDetail_sku_right'> <AtIcon value='chevron-right' size='30' color='#F00'></AtIcon> </View>
        </View>}
        <View className='ShopDetail_rectText'>
          <Tabs classNames='tan_classname' list={tabList} stretch={false} onChange={(e) => { setActiveKey(e) }} activeKey={activeKey}>
          </Tabs>
          <Space style={{ width: '100%' }} direction='vertical'>
            {renderContent}
          </Space>
        </View>
        {renderButton()}
        <SelectSku submit={(data) => {
          setSkuData({
            ...skuData,
            ...data
          })
        }} defaultData={selectobj} sukSelectData={selectData} show={visible} data={data} onClose={() => setVisible(false)}></SelectSku>
        <Contain list={goodsPackageList} show={containVisible} onClose={() => setContainVisible(false)}></Contain>
      </View>
      <MaskCode visible={maskCodeVisible} onClose={() => setMaskCodeVisible(false)} submit={() => {
        setMaskCodeVisible(false)
        reload()
      }}></MaskCode>
    </View>
  )
}
export default offline